package com.aipartner.mapper;

import com.aipartner.entity.CreditsTransaction;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 积分交易记录 Mapper 接口
 *
 * @author AI Partner
 * @since 2025-09-18
 */
@Mapper
public interface CreditsTransactionMapper extends BaseMapper<CreditsTransaction> {

    /**
     * 分页查询用户积分交易记录
     */
    @Select("SELECT * FROM credits_transactions WHERE user_id = #{userId} ORDER BY create_time DESC")
    IPage<CreditsTransaction> selectByUserIdPage(Page<?> page, @Param("userId") Long userId);

    /**
     * 查询用户指定类型的积分交易记录
     */
    @Select("SELECT * FROM credits_transactions WHERE user_id = #{userId} AND transaction_type = #{transactionType} ORDER BY create_time DESC")
    List<CreditsTransaction> selectByUserIdAndType(@Param("userId") Long userId, @Param("transactionType") String transactionType);

    /**
     * 查询用户积分统计
     */
    @Select("SELECT " +
            "SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) as totalEarned, " +
            "SUM(CASE WHEN amount < 0 THEN -amount ELSE 0 END) as totalConsumed " +
            "FROM credits_transactions WHERE user_id = #{userId}")
    CreditsTransaction selectUserCreditsStats(@Param("userId") Long userId);

    /**
     * 查询即将过期的积分
     */
    @Select("SELECT * FROM credits_transactions " +
            "WHERE user_id = #{userId} " +
            "AND transaction_type = 'purchase' " +
            "AND expire_time BETWEEN #{startTime} AND #{endTime} " +
            "AND status = 'completed'")
    List<CreditsTransaction> selectExpiringCredits(@Param("userId") Long userId, 
                                                   @Param("startTime") LocalDateTime startTime, 
                                                   @Param("endTime") LocalDateTime endTime);
}
